package com.wt.hrentSystem.hrent.controller;

import com.wt.hrentSystem.common.config.ResponseCodeCanstants;
import com.wt.hrentSystem.common.entity.Page;
import com.wt.hrentSystem.common.entity.ResponseResult;
import com.wt.hrentSystem.common.entity.User;
import com.wt.hrentSystem.common.util.UserUtils;
import com.wt.hrentSystem.hrent.entity.ApplyRent;
import com.wt.hrentSystem.hrent.entity.ApplyView;
import com.wt.hrentSystem.hrent.entity.BikeResource;
import com.wt.hrentSystem.hrent.service.ApplyRentService;
import com.wt.hrentSystem.hrent.service.BikeResourceService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("applyRent")
public class ApplyRentController{
    @Resource
    private ApplyRentService applyRentService;

    @Resource
    private BikeResourceService bikeResourceService;

    @Autowired
    private UserUtils userUtils;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 日期格式
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    // 日期时间格式
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    /**
     * 根据id查询单条数据
     */
    @RequestMapping("get")
    public ResponseResult<ApplyRent> get(String id){
        ApplyRent applyRent = applyRentService.get(id);
        return new ResponseResult(ResponseCodeCanstants.SUCCESS,applyRent,"成功");
    }


    /**
     * 通过ID查询单条数据,JSON
     */
    @RequestMapping("wechatGet")
    public ResponseResult<ApplyRent> wechatGet(@RequestBody ApplyRent applyRent,HttpServletRequest request){
        ResponseResult<ApplyRent> applyRentResponseResult = get(applyRent.getId());
        ApplyRent resultData = applyRentResponseResult.getData();
        User user = userUtils.getUser(request);
        if (user != null){
            BigDecimal latitude = user.getLatitude();
            BigDecimal longitude = user.getLongitude();
            resultData.getBikeResource().setUserLatitude(latitude);
            resultData.getBikeResource().setUserLongitude(longitude);
        }
        applyRentResponseResult.setData(resultData);
        return applyRentResponseResult;
    }

    /**
     *分页查询
     */
    @RequestMapping("findPage")
    public ResponseResult<Page> findPage(ApplyRent applyRent, HttpServletRequest request, HttpServletResponse response){
        applyRent.setCurrentUser(userUtils.getUser(request));
        Page<ApplyRent> page = new Page<>(request, response);
        Page<ApplyRent> page1 = applyRentService.findPage(page, applyRent);
        return new ResponseResult(ResponseCodeCanstants.SUCCESS,page1,"成功");
    }

    /**
     * 查询所有
     */
    @RequestMapping("findAll")
    public ResponseResult<List<ApplyRent>> findAll(ApplyRent applyRent){
        List<ApplyRent> list = applyRentService.findList(applyRent);
        return new ResponseResult<>(ResponseCodeCanstants.SUCCESS,list,"成功");
    }

    /**
     * 增加或修改
     */
    @RequestMapping("save")
    public ResponseResult save(@RequestBody ApplyRent applyRent, HttpServletRequest request) throws ParseException {
        applyRent.setCurrentUser(userUtils.getUser(request));
        // long  short
        String startDate = applyRent.getStartDate();
        String endDate = applyRent.getEndDate();

        String bikeId = applyRent.getBikeId();
        if (!StringUtils.isEmpty(bikeId)){
            String rentType = applyRent.getRentType();
            BikeResource bikeResource = bikeResourceService.get(bikeId);
            if (rentType.equals("long")){
                applyRent.setStartTime(formatter.parse(startDate + " 00:00:00"));
                applyRent.setEndTime(formatter.parse(endDate + " 00:00:00"));
                // 获取月-费用
                Double rentingMonth = bikeResource.getRentingMonth();
                double amount = calculateRentAmount(startDate, endDate, rentingMonth);
                applyRent.setMoney(amount);
            }else{
                // 获取 日-费用
                // short
                applyRent.setStartTime(formatter.parse(startDate+":00"));
                applyRent.setEndTime(formatter.parse(endDate+":00"));
                Double rentingHour = bikeResource.getRentingHour();
                double amount = calculateHourlyRent(startDate, endDate, rentingHour);
                applyRent.setMoney(amount);
            }
        }

        applyRentService.save(applyRent);
        // 修改bikeRenting


        return new ResponseResult(ResponseCodeCanstants.SUCCESS,"成功");
    }

    /**
     * 删除
     */
    @RequestMapping("delete")
    public ResponseResult delete(ApplyRent applyRent,HttpServletRequest request){
        applyRent.setCurrentUser(userUtils.getUser(request));
        applyRentService.delete(applyRent);
        return new ResponseResult(ResponseCodeCanstants.SUCCESS,"成功");
    }

    /**
     * 查询个人的申请租车信息
     */
    @RequestMapping("findPersonalRentApply")
    public ResponseResult findPersonalRentApply(@RequestBody ApplyRent applyRent,HttpServletRequest request,HttpServletResponse response){
        User user = userUtils.getUser(request);
        applyRent.setCurrentUser(user);
        Page<ApplyRent> page = new Page<>(applyRent.getPageNo(), applyRent.getPageSize());
        Page<ApplyRent> page1 = applyRentService.findPersonalViewApply(page, applyRent);

        List<ApplyRent> collect = page1.getList().stream().map(item -> {
            if (user != null) {
                BigDecimal latitude = user.getLatitude();
                BigDecimal longitude = user.getLongitude();
                item.getBikeResource().setUserLatitude(latitude);
                item.getBikeResource().setUserLongitude(longitude);
            }
            return item;
        }).collect(Collectors.toList());

        return new ResponseResult(ResponseCodeCanstants.SUCCESS,page1,"查询成功");
    }

    /**
     * 成功支付押金之后调用的接口
     */
    @RequestMapping("paySuccess")
    public ResponseResult  paySuccess(@RequestBody ApplyRent applyRent,HttpServletRequest request){
        applyRent.setCurrentUser(userUtils.getUser(request));
        try {
            applyRentService.paySuccess(applyRent);
            return new ResponseResult(ResponseCodeCanstants.SUCCESS,"成功");
        }catch (Exception e){
            e.printStackTrace();
        }

        return new ResponseResult(ResponseCodeCanstants.FAILED,"成功");
    }

    /**
     * 根据车辆Id和用户id查询是否有租车申请
     */
    @RequestMapping("getByEntity")
    public ResponseResult getByEntity(@RequestBody ApplyRent applyRent){
        return new ResponseResult(ResponseCodeCanstants.SUCCESS,applyRentService.getByEntity(applyRent),"成功");
    }

    /**
     * 计算租赁费用
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate 结束日期 (格式: yyyy-MM-dd)
     * @param rentingMonth 月租金
     * @return 总租金金额
     */
    public static double calculateRentAmount(String startDate, String endDate, double rentingMonth) {
        // 解析日期
        LocalDate start = LocalDate.parse(startDate, DATE_FORMATTER);
        LocalDate end = LocalDate.parse(endDate, DATE_FORMATTER);

        // 计算完整月份数
        long fullMonths = ChronoUnit.MONTHS.between(
                start.withDayOfMonth(1),
                end.withDayOfMonth(1)
        );

        // 计算开始月份和结束月份的天数比例
        double partialMonths = 0.0;

        // 处理开始月份(如果不是1号开始)
        if (start.getDayOfMonth() != 1) {
            int daysInStartMonth = start.lengthOfMonth();
            int daysUsed = daysInStartMonth - start.getDayOfMonth() + 1;
            partialMonths += (double) daysUsed / daysInStartMonth;
        }

        // 处理结束月份(如果不是月末结束)
        if (end.getDayOfMonth() != end.lengthOfMonth()) {
            int daysInEndMonth = end.lengthOfMonth();
            int daysUsed = end.getDayOfMonth();
            partialMonths += (double) daysUsed / daysInEndMonth;
        }

        // 计算总金额
        double totalAmount = fullMonths * rentingMonth;
        if (partialMonths > 0) {
            totalAmount += partialMonths * rentingMonth;
        }

        return totalAmount;
    }

    /**
     * 计算小时租赁费用
     * @param startDateTime 开始日期时间 (格式: yyyy-MM-dd HH:mm)
     * @param endDateTime 结束日期时间 (格式: yyyy-MM-dd HH:mm)
     * @param rentingHour 每小时租金
     * @return 总租金金额
     */
    public static double calculateHourlyRent(String startDateTime,
                                             String endDateTime,
                                             double rentingHour) {
        // 解析日期时间
        LocalDateTime start = LocalDateTime.parse(startDateTime, DATE_TIME_FORMATTER);
        LocalDateTime end = LocalDateTime.parse(endDateTime, DATE_TIME_FORMATTER);

        // 计算总小时数(向上取整)
        long totalHours = ChronoUnit.HOURS.between(start, end);

        // 如果有不足1小时的分钟数，按1小时计算
        long remainingMinutes = ChronoUnit.MINUTES.between(start, end) % 60;
        if (remainingMinutes > 0) {
            totalHours += 1;
        }

        // 计算总金额
        return totalHours * rentingHour;
    }

}
